from flask import Blueprint, url_for, render_template, request, current_app,redirect, abort, flash
from app import db
from app.utils.common import login_required
from app.utils.util import create_nonce_str, create_password
from app.models import Category
from app.constants import PAGE_LIMIT
from app.forms import CategoryForm
from datetime import datetime

category_controller = Blueprint("category", __name__)

@category_controller.route("/category/index")
@login_required
def category():
    page = request.args.get("page", 1, type=int)
    try:
        pagination = Category.query.order_by(Category.id.desc()).paginate(page, per_page=PAGE_LIMIT)
    except Exception as e:
        current_app.logger.error(e)
        flash("获取栏目失败")

    return render_template('admin/category/index.html', pagination=pagination)

@category_controller.route("/category/add", methods=['GET', 'POST'])
@login_required
def add_category():
    form = CategoryForm()
    if request.method == "POST":
        if form.validate_on_submit():
            catname = form.data.get('catname')
            sort = form.data.get('sort')
            try:
                tag = Category(catname=catname, sort= sort if sort > 0 else 0)
                db.session.add(tag)
                db.session.commit()
            except Exception as e:
                current_app.logger.error(e)
                flash("添加栏目失败")
            return redirect(url_for('category.category'))
        
    return render_template("admin/category/add.html", form=form)

@category_controller.route("/category/edit", methods=['GET', 'POST'])
@login_required
def edit_category():
    id = request.args.get("id", 0)
    try:
        category = Category.query.filter_by(id=id).first()
    except Exception as e:
        current_app.logger.error(e)
        flash("栏目不存在")
        return redirect(url_for('category.category'))

    form = CategoryForm()
    if request.method == "POST":
        if form.validate_on_submit():
            catname = form.data.get('catname')
            sort = form.data.get('sort')
            category.catname = catname
            category.sort = sort if sort > 0 else 0
            category.update_time = datetime.now()
            try:
                db.session.add(category)
                db.session.commit()
            except Exception as e:
                current_app.logger.error(e)
                flash("编辑栏目失败")
            return redirect(url_for('category.category'))
        
    return render_template("admin/category/edit.html", form=form, category=category)

@category_controller.route("/category/delete", methods=['GET'])
@login_required
def del_category():
    id = request.args.get("id", 0, type=int)
    try:
        category = Category.query.filter_by(id=id).first()
    except Exception as e:
        current_app.logger.error(e)
        flash("栏目不存在")
        return redirect(url_for('category.category'))
    
    if category.articles.length == 0:
        try:
            db.session.delete(category)
            db.session.commit()
        except Exception as e:
            current_app.logger.error(e)
            flash("删除栏目失败")
    else:
        flash("栏目下有文章，不能删除")

    return redirect(url_for('category.category'))